import 'package:flutter/material.dart';
import '../config/config.dart';
import '../utils/HttpRequest.dart';

/// 用户搜索页面组件
class UserSearchPage extends StatefulWidget {
  /// 创建UserSearchPage实例
  const UserSearchPage({super.key});

  @override
  /// 创建页面状态管理对象
  State<UserSearchPage> createState() => _UserSearchPageState();
}

/// UserSearchPage的状态管理类
class _UserSearchPageState extends State<UserSearchPage> {
  /// 构造函数，初始化默认的token值
  _UserSearchPageState() {
    _tokenController.text = AppConfig.demoToken;
  }

  /// 输入框控制器：存储搜索关键字
  final _keywordController = TextEditingController();
  
  /// 输入框控制器：存储用户的Access Token
  final _tokenController = TextEditingController();
  
  /// 表单验证的全局键
  final _formKey = GlobalKey<FormState>();
  
  /// GitCode API客户端实例，用于发送网络请求
  final _client = GitCodeApiClient();

  /// 用户搜索结果列表
  List<GitCodeSearchUser> _userResults = const [];
  
  /// 错误信息，用于展示API调用失败时的提示
  String? _errorMessage;
  
  /// 加载状态标志，控制加载指示器的显示
  bool _isLoading = false;
  
  /// 控制token输入框是否显示为密码形式
  bool _obscureToken = true;

  @override
  /// 释放资源，清理控制器
  void dispose() {
    _keywordController.dispose();
    _tokenController.dispose();
    super.dispose();
  }

  /// 执行用户搜索
  Future<void> _performSearch() async {
    // 防止重复提交
    if (_isLoading) return;
    
    // 验证表单
    if (!_formKey.currentState!.validate()) return;

    // 收起键盘
    FocusScope.of(context).unfocus();

    // 重置状态，显示加载指示器
    setState(() {
      _isLoading = true;
      _errorMessage = null;
      _userResults = const [];
    });

    // 获取token值
    final token = _tokenController.text.trim();

    try {
      // 执行用户搜索API请求
      final users = await _client.searchUsers(
        keyword: _keywordController.text,
        personalToken: token,
        perPage: 8,
      );
      setState(() {
        _userResults = users;
      });
    } on GitCodeApiException catch (error) {
      // 处理特定的API异常
      setState(() {
        _errorMessage = error.message;
      });
    } catch (error) {
      // 处理其他未预期的异常
      setState(() {
        _errorMessage = '未知错误：$error';
      });
    } finally {
      // 确保在组件仍挂载时更新状态
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  /// 构建页面UI布局
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('用户搜索'),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(20),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildIntro(),
              const SizedBox(height: 20),
              _buildFormCard(),
              const SizedBox(height: 20),
              _buildResultSection(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建页面介绍文本组件
  Widget _buildIntro() {
    return const Text(
      '输入关键字 + access token，立即查询 GitCode 用户（搜索接口需授权）。',
      style: TextStyle(fontSize: 15, fontWeight: FontWeight.w500),
    );
  }

  /// 构建搜索表单卡片
  Widget _buildFormCard() {
    return Card(
      elevation: 0,
      clipBehavior: Clip.antiAlias,
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              TextFormField(
                controller: _keywordController,
                textInputAction: TextInputAction.search,
                decoration: const InputDecoration(
                  labelText: '搜索关键字',
                  hintText: '例如：iflytek',
                  prefixIcon: Icon(Icons.search),
                ),
                validator: (value) {
                  if (value == null || value.trim().isEmpty) {
                    return '请输入关键字';
                  }
                  return null;
                },
                onFieldSubmitted: (_) => _performSearch(),
              ),
              const SizedBox(height: 12),
              TextFormField(
                controller: _tokenController,
                decoration: InputDecoration(
                  labelText: 'Access Token',
                  hintText: 'GitCode 个人设置 > Access Token',
                  prefixIcon: const Icon(Icons.vpn_key_outlined),
                  suffixIcon: IconButton(
                    icon: Icon(
                      _obscureToken
                          ? Icons.visibility_off_outlined
                          : Icons.visibility_outlined,
                    ),
                    onPressed: () {
                      setState(() {
                        _obscureToken = !_obscureToken;
                      });
                    },
                  ),
                ),
                obscureText: _obscureToken,
                validator: (value) {
                  if (value == null || value.trim().isEmpty) {
                    return '搜索接口需提供 access token';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              FilledButton.icon(
                onPressed: _isLoading ? null : _performSearch,
                icon: _isLoading
                    ? const SizedBox(
                        width: 18,
                        height: 18,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      )
                    : const Icon(Icons.play_arrow_rounded),
                label: Text(_isLoading ? '查询中...' : '查询'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建结果展示区域
  Widget _buildResultSection() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_errorMessage != null) {
      // 显示错误信息
      return _InfoBanner(
        icon: Icons.error_outline,
        background: Colors.red.withOpacity(0.08),
        textColor: Colors.red.shade700,
        message: _errorMessage!,
      );
    }

    return _buildUserResults();
  }

  /// 构建用户搜索结果列表
  Widget _buildUserResults() {
    if (_userResults.isEmpty) {
      return const _InfoBanner(
        icon: Icons.info_outline,
        background: Color(0xFFEFF4FF),
        textColor: Color(0xFF1A237E),
        message: '暂无数据，输入关键字并点击“查询”试试。',
      );
    }

    return Column(
      children: _userResults.map(_UserTile.new).toList(),
    );
  }
}

/// 信息横幅组件
class _InfoBanner extends StatelessWidget {
  /// 创建信息横幅组件
  const _InfoBanner({
    required this.icon,
    required this.background,
    required this.textColor,
    required this.message,
  });

  /// 显示的图标
  final IconData icon;
  
  /// 背景颜色
  final Color background;
  
  /// 文字颜色
  final Color textColor;
  
  /// 要显示的消息内容
  final String message;

  @override
  /// 构建信息横幅UI
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: background,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Icon(icon, color: textColor),
          const SizedBox(width: 12),
          Expanded(
            child: Text(
              message,
              style: Theme.of(context)
                  .textTheme
                  .bodyMedium
                  ?.copyWith(color: textColor),
            ),
          ),
        ],
      ),
    );
  }
}

/// 用户信息卡片组件
class _UserTile extends StatelessWidget {
  /// 创建用户信息卡片
  const _UserTile(this.user);

  /// 用户搜索结果数据
  final GitCodeSearchUser user;

  @override
  /// 构建用户信息卡片UI
  Widget build(BuildContext context) {
    // 优先显示用户的真实名称，如果没有则显示登录名
    final title = user.name?.isNotEmpty == true ? user.name! : user.login;
    // 构建副标题内容，包含登录名和创建时间
    final subtitleParts = <String>[
      '@${user.login}',
      if (user.createdAt != null) '注册 ${user.createdAt}',
    ];

    return Card(
      elevation: 0,
      margin: const EdgeInsets.only(bottom: 12),
      child: ListTile(
        // 用户头像，处理可能的加载错误
        leading: CircleAvatar(
          // GitCode 头像 URL 直接展示，失败时忽略错误防止闪退。
          backgroundImage: NetworkImage(user.avatarUrl),
          onBackgroundImageError: (_, __) {},
        ),
        // 用户名标题
        title: Text(title, style: const TextStyle(fontWeight: FontWeight.w600)),
        // 用户详细信息
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 显示登录名和注册时间
            Text(
              subtitleParts.join(' · '),
              style: const TextStyle(fontSize: 12),
            ),
            // 显示用户的个人主页URL
            if (user.htmlUrl != null)
              Text(
                user.htmlUrl!,
                style: const TextStyle(fontSize: 12, color: Colors.blue),
              ),
          ],
        ),
      ),
    );
  }
}